<template>
  <el-form
    ref="ruleFormRef"
    style="width: 300px"
    :model="ruleForm"
    :rules="rules"
    class="register-form"
  >
    <el-form-item label="" prop="username">
      <el-input v-model="ruleForm.username" placeholder="请输入用户名" />
    </el-form-item>
    <el-form-item label="" prop="password">
      <el-input v-model="ruleForm.password" type="password" placeholder="请输入密码" />
    </el-form-item>
    <el-button type="primary" @click="submitForm(ruleFormRef)"> 登录 </el-button>
  </el-form>
  <p class="tips" @click="changeType">没有账号？去注册</p>
</template>

<script lang="ts" setup>
import { defineEmits, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { userLogin } from '@/api/user'

const ruleFormRef = ref<FormInstance>()

const emit = defineEmits(['change', 'success'])

const checkUsername = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入用户名'))
  }
  // 只能输入数字、字母、下划线
  const reg = /^[a-zA-Z0-9_]+$/
  if (!reg.test(value)) {
    callback(new Error('只能输入数字、字母、下划线'))
  } else {
    callback()
  }
}

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    callback()
  }
}

const ruleForm = reactive({
  password: '',
  username: '',
})

const rules = reactive<FormRules<typeof ruleForm>>({
  username: [{ validator: checkUsername, trigger: 'blur' }],
  password: [{ validator: validatePass, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      console.log('submit!')
      const res = await userLogin(ruleForm)
      console.log('res: ', res)
      localStorage.setItem('token', res?.token)
      if (res) {
        ElMessage({
          message: '登录成功',
          type: 'success',
        })
        emit('success', res?.token)
      }
    } else {
      console.log('error submit!')
    }
  })
}

const changeType = () => {
  emit('change', 'register')
}
</script>
<script lang="ts">
export default {
  name: 'Login',
}
</script>
<style lang="less" scoped>
.register-form {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  width: 300px;
  .el-form-item {
    margin-bottom: 20px;
    width: 100%;
    .el-input {
      height: 40px;
    }
  }
  .el-button {
    width: 100%;
  }
}
.tips {
  text-align: center;
  margin-top: 20px;
  cursor: pointer;
  color: #409eff;
}
</style>
